package org.gitman.agentplatform.ui.actions;

import java.awt.event.ActionEvent;

import org.gitman.agentplatform.agent.api.Agent;
import org.gitman.agentplatform.agent.api.InternalAgentInfo;
import org.gitman.agentplatform.core.AgentManager;
import org.gitman.agentplatform.core.exceptions.NoGraphException;
import org.gitman.agentplatform.ui.api.View;
import org.gitman.agentplatform.ui.api.View.MessageType;
import org.gitman.agentplatform.ui.simulation.SimulationPanel;

public class OkAddingAgentAction extends UIAction{

	public OkAddingAgentAction() {
		super("ok");
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		InternalAgentInfo info = null;
		Class<? extends Agent> clazz = null;
		String args = null;
		try{
		
			if(platformManager.getSimulation().getGraph() == null){
				throw new NoGraphException();
			}else{
				SimulationPanel simulationPanel = mainFrame.getSimulationPanel();
				clazz = simulationPanel.getAgentClass();
				info = simulationPanel.getAgentInfo();
				args = simulationPanel.getArgs();	
				AgentManager agentManager = platformManager.getSimulation().getAgentManager();	
				
				
				if(platformManager.getSimulation().verifyAgentInfo(info)){
					if(simulationPanel.isAgentEdited()){
						agentManager.removeAgent(info.getId());
						platformManager.getView().colourVertex(simulationPanel.getPrevID(), null);
						
					}					
					platformManager.getView().colourVertex(info.getStartVertexID(), info.getColor());
					agentManager.addAgent(info, clazz, args);
					simulationPanel.fireTableChanged();
					mainFrame.getSimulationPanel().hideDetailsPanel();
				}
			}
		}catch(NumberFormatException e2){
			View.showMessage("Can not create agent. One of the agent parametrs\n" +
							 "has wrong format or is missing.", MessageType.ERROR);
			e2.printStackTrace();
		}catch(Exception ex){
			View.showMessage(ex.getMessage(), MessageType.ERROR);
			ex.printStackTrace();
		}
			
	}

}
